

function red() {
    axios.get('/my/category/list').then(res => {
        // console.log(res.data);
        let { status, data } = res.data
        if (status === 0) {
            let str = ''
            // 遍历炫染数据
            data.forEach(item => {
                str += `
                
                <tr>
            <td>${item.name}</td>
            <td>${item.alias}</td>
            <td>
              <button data-id="${item.id}" data-name="${item.name}" data-alias="${item.alias}"type="button" class="layui-btn layui-btn-xs bianji">编辑</button>
              <button data-id="${item.id}" type="button" class="del layui-btn layui-btn-xs layui-btn-danger">删除</button>
            </td>
          </tr>
                
                
                `
            });
            $('tbody').html(str)
        }
    })
}
red()

// ----------------------------删除类别---------------------

$('tbody').on('click', '.del', function () {
    // $(this)表示删除的按钮

    let id = $(this).data('id');

    layer.confirm('确定删除？', { icon: 3, title: '提示' }, function (index) {
        //do something
        axios.get(`/my/category/delete?id=${id}`).then(res => {
            let { status, message } = res.data
            if (status === 0) {
                layer.msg(message)
                red()
            }
        })
        layer.close(index);

    })
})

// ---------------------添加类别--------------------

let addIndex;
// 1. 添加 添加类别 按钮，出现弹层
$('.add').on('click', function () {
  addIndex = layer.open({
    type: 1,
    title: '添加类别',
    content: $('#tpl-add').html(),
    area: ['500px', '250px']
  });
})


// 注册表单事件完成添加
$('body').on('submit','#add-form',function(e){
    e.preventDefault()

    let data = $(this).serialize()

    axios.post('/my/category/add',data).then(res=>{

        let {status,message} = res.data

        if(status === 0 ) {
            layer.msg(message)
            red()
        }
        layer.close(addIndex)

    })
})



// ----------------编辑类别------------------

// 数据回填

$('tbody').on('click','.bianji',function(){
    // 获取所有Data-属性
    let sj = $(this).data()
    // 点击出现弹出层
    editIndex = layer.open({
        type: 1,
        title: '修改类别',
        // 弹出层内容
        content: $('#tpl-edit').html(),
        area: ['500px', '250px'],
        // 弹出层弹出后再进行数据回填
        success: function(){
            let form = layui.form
            // 加载layui的form模块
        
            form.val('abc',sj)
        }
      });
})


// 修改

$('body').on('submit','#edit-form',function(e){
    e.preventDefault()
    let data = $(this).serialize()

    axios.post('/my/category/update',data).then(res=>{
        let {status,message} = res.data
        if(status ===0) {
          layer.msg(message)
          red()
        }
        layer.close(editIndex)
    })
})